import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.DataInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

/*
 * User handling class
 */
public class User {

	private boolean _isAdmin;
	private String uname = new String();
	private String password = new String();
	private ArrayList<String> userlist = new ArrayList<String>();
	private ArrayList<String> passwordlist = new ArrayList<String>();
	private FileInputStream fis;
	private File f = new File("admins.txt");
	
	//Method for a standard user//
	public User()
	{
		this._isAdmin = false;
		this.uname = "Unbekannter User";
	}
	
	/*
	 * Loads our whole data and stores it in the
	 * object
	 */
	public User(String uname, String password)
	{
		this.uname = uname;
		this.password = password;
		//Get all users from file//		
		try 
		{
			//Datei existiert nicht -> neue erstellen//
			if(!f.exists())
			f.createNewFile();
			//Datei oeffnen//
			this.fis = new FileInputStream( "admins.txt" ); 
			DataInputStream in = new DataInputStream( fis );
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			  
			String strLine;
			while((strLine = br.readLine()) != null)
			{
				//Uname und pw delimited by " "//
				String line[] = strLine.split(" ");
									
				this.userlist.add(line[0]);
				this.passwordlist.add(line[1]);
			}
		}
		catch ( IOException e ) 
		{ }
		finally 
		{ 
			try 
			{ 
				this.fis.close(); 
			} 
			catch ( Exception e ) { }
		}
		
		//Authentication//
		if(this.authenticate())
			this._isAdmin = true;
		else
			this._isAdmin = false;
	}
	
	/*
	 * Schaut nach ob aktuellen Werte uname / pw mit irgendwas im 
	 * Array uebereinstimmen
	 */
	private boolean authenticate()
	{
		for(int i = 0; i < this.userlist.size(); i++)
		{	
			//Go through all stored users and authenticate//
			if(this.userlist.get(i).equals(this.uname) && this.passwordlist.get(i).equals(this.password))
				return true;
		}
		
		return false;
	}
	
	public boolean isAdmin()
	{
		return this._isAdmin;
	}
	
	public String getName()
	{
		return this.uname;
	}
}
